package yishop.service.impl;

import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.util.StringUtils;
import yishop.dao.ITbUserDao;
import yishop.dao.UserMapper;
import yishop.entity.dto.UserDto;
import yishop.service.ITbUserService;
import yishop.entity.PageData;
import yishop.utils.ExcelUtil;
import yishop.utils.MD5Util;
import yishop.utils.PageUtil;

import java.util.Date;
import java.util.LinkedHashMap;

import yishop.entity.UserEntity;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TbUserService implements ITbUserService {


    private ITbUserDao dao;

    @Autowired
    public TbUserService(ITbUserDao dao) {
        this.dao = dao;
    }
    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(UserEntity entity) {
        log.info("TbUserEntity:{}", entity);
        entity.setCreateDate(new Date());
        if (!StringUtils.isEmpty(entity.getPassword())) {
            //MD5加密
            entity.setPassword(MD5Util.encodeByMd5(entity.getPassword()));
        }
        //dao.add(entity);
        userMapper.insert(entity);
    }

    @Override
    public void delete(UserDto userDto) {
        if(userDto.getId()==null){
            log.error("id不能为空");

        }
        userMapper.deleteById(userDto.getId());

    }

    @Override
    public void update(UserEntity entity) {
        dao.update(entity);
    }

    @Override
    public List<UserEntity> select(UserEntity entity) {
        return dao.select(entity);
    }

    @Override
    public PageData<UserEntity> likeSelect(UserEntity entity) {

        return PageUtil.getPageData(entity, dao);
    }

    @Override
    public void batchAdd(List<UserEntity> list) {
        dao.batchAdd(list);
    }

    @Override
    public void batchDelete(List<UserEntity> list) {
        dao.batchDelete(list);
    }

    @Override
    public void batchUpdate(List<UserEntity> list) {
        dao.batchUpdate(list);
    }


    @Override
    public void exportExcel(UserEntity entity, HttpServletResponse response) {

        // 获取头部信息（可以设置为动态）
        String[] headList = new String[]{"id", "用户名", "密码", "年龄", "性别", "等级", "创建时间"};

        String[] headEngList = new String[]{"id", "username", "password", "age", "sex", "grade", "createDate"};

        String[] describeList = new String[]{"", "", "", "", "", "", ""};

        //设置头部以及描述信息
        Map<String, String> headAndDescribeMap = new LinkedHashMap<>();
        for (int i = 0; i < headEngList.length; i++) {
            headAndDescribeMap.put(headEngList[i], describeList[i]);
        }

        ExcelUtil.exportExcel(entity, response, dao, headList, headAndDescribeMap);
    }
}
